package datastructure.array;

/**
 *
 * @author Lei Zhang
 */
public class MergeSortedArrays {
  public static int[] mergeSortedArrays(int[] a1, int[] a2) {

    if (a1 == null || a2 == null) {
      throw new IllegalArgumentException("null");
    }

    int[] ret = new int[a1.length + a2.length];
    int i = 0;
    int j = 0;
    int m = 0;
    while (i < a1.length && j < a2.length) {
      if (a1[i] <= a2[j]) {
        ret[m] = a1[i];
        i++;
      } else {
        ret[m] = a2[j];
        j++;
      }
      m++;
    }

    while (i < a1.length) {
      ret[m] = a1[i];
      i++;
      m++;
    }

    while (j < a2.length) {
      ret[m] = a2[j];
      j++;
      m++;
    }

    return ret;

  }

  public static void main(String args[]) {

    int[] anArray1 = {
      2,
      5,
      7,
      8,
      10,
      16,
      17,};

    int[] anArray2 = {
      3,
      5,
      7,
      9,
      10,
      16,
      19,};


    int[] ret = MergeSortedArrays.mergeSortedArrays(anArray1,
        anArray2);

    for (int i = 0; i < ret.length; i++) {
      System.out.println(ret[i]);
    }
  }
}
